package com.gsoe.auth.utils;

import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

public class FileUtils {

    public static String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String getFileMD5(InputStream inputStream) throws IOException {
        return DigestUtils.md5DigestAsHex(inputStream);
    }

    public static String getFilePathByFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix = getFileSuffix(fileName);
        String fileMD5 = getFileMD5(file.getInputStream());
        return "/"+fileMD5.charAt(0)+"/"+fileMD5.charAt(1)+"/"+fileMD5+"."+suffix;
    }

    public static boolean checkImageSuffix(String fileSuffix) {
        String[] imageSuffix ={"jpg","jpeg","png","gif"};
        fileSuffix = fileSuffix.toLowerCase();
        for (String suffix : imageSuffix) {
            if(fileSuffix.equals(suffix)) {return true;}
        }
        return false;
    }
}
